//
//  IAPManager.swift
//  GhostWorld
//
//  Created by Kam on 2018/6/8.
//  Copyright © 2018 LKGood. All rights reserved.
//

import Foundation
import SwiftyStoreKit

struct IAPReceiptItem {
  var isTrialPeriod: String
  var productID: String
  var originalPurchaseTimestamp: String
  var originalTransactionID: String
  var quantity: String
  var date: Date?
}

class IAPManger {
  // MARK: - Singleton
  static let shared = IAPManger()
  private init() { }
  
  func prepare() {
    // add IAP transaction observer
    SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
      for purchase in purchases {
        switch purchase.transaction.transactionState {
        case .purchased, .restored:
          if purchase.needsFinishTransaction {
            // Deliver content from server, then:
            SwiftyStoreKit.finishTransaction(purchase.transaction)
          }
        // Unlock content
        case .failed, .purchasing, .deferred:
          break // do nothing
        }
      }
    }
  }
  
  func validReceipts(completion: @escaping ([IAPReceiptItem]) -> Void) {
    let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "your-shared-secret")
    SwiftyStoreKit.verifyReceipt(using: appleValidator, forceRefresh: false) { result in
      switch result {
      case .success(let receipt):
        if let inApp = receipt["receipt"]?["in_app"] as? [[String: Any]] {
          var iapReceiptItems = [IAPReceiptItem]()
          inApp.forEach {
            let dateString = $0["original_purchase_date"] as! String
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss VV"
            let date = dateFormatter.date(from: dateString)
            
            let item = IAPReceiptItem (
              isTrialPeriod: $0["is_trial_period"] as! String,
              productID: $0["product_id"] as! String,
              originalPurchaseTimestamp: $0["original_purchase_date_ms"] as! String,
              originalTransactionID: $0["original_transaction_id"] as! String,
              quantity: $0["quantity"] as! String,
              date: date
            )
            iapReceiptItems.append(item)
          }
          completion(iapReceiptItems)
        }
      case .error(let error):
        loggingPrint("Verify receipt failed: \(error)")
      }
    }
  }
}
